package com.sdhs.costcontrol.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sdhs.common.enums.BusinessStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sdhs.common.utils.DateUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.costcontrol.domain.GcControlConfirmationPurchase;
import com.sdhs.costcontrol.domain.GcControlConfirmationPurchaseList;
import com.sdhs.costcontrol.domain.GcControlPlanList;
import com.sdhs.costcontrol.domain.GcControlPurchasePlan;
import com.sdhs.costcontrol.mapper.GcControlConfirmationPurchaseListMapper;
import com.sdhs.costcontrol.mapper.GcControlConfirmationPurchaseMapper;
import com.sdhs.costcontrol.mapper.GcControlPlanListMapper;
import com.sdhs.costcontrol.mapper.GcControlPurchasePlanMapper;
import com.sdhs.costcontrol.service.IGcControlPurchasePlanService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollectionUtil;

/**
 * 成本控制--采购计划Service业务层处理
 *
 * @author andong
 * @date 2025-03-13
 */
@Service
public class GcControlPurchasePlanServiceImpl implements IGcControlPurchasePlanService {
    @Autowired
    private GcControlPurchasePlanMapper gcControlPurchasePlanMapper;

    @Autowired
    private GcControlPlanListMapper gcControlPlanListMapper;

    @Autowired
    private GcControlConfirmationPurchaseMapper gcControlConfirmationPurchaseMapper;

    @Autowired
    private GcControlConfirmationPurchaseListMapper gcControlConfirmationPurchaseListMapper;
    /**
     * 查询成本控制--采购计划
     *
     * @param id 成本控制--采购计划主键
     * @return 成本控制--采购计划
     */
    @Override
    public GcControlPurchasePlan selectGcControlPurchasePlanById(Long id) {
        GcControlPurchasePlan gcControlPurchasePlan = gcControlPurchasePlanMapper.selectGcControlPurchasePlanById(id);
        if (gcControlPurchasePlan == null) {
            return null;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("projectId", gcControlPurchasePlan.getProjectId());
        params.put("procurementType", gcControlPurchasePlan.getProcurementType());

        // 获取采购计划列表
        List<GcControlPlanList> gcControlPlanLists = gcControlPlanListMapper.selectGcControlPlanByTwoIdList(params);

        // 处理purchaseIds转换
        String purchaseIds = gcControlPurchasePlan.getPurchaseIds();
        if(purchaseIds==null){
            // 当purchaseIds为null时，将所有TotalArrivalQuantity设为0
            gcControlPlanLists.forEach(plan -> plan.setTotalArrivalQuantity(BigDecimal.ZERO));
        }else {

            Long[]  purchaseIdArray = Arrays.stream(purchaseIds.split(","))
                            .map(String::trim)
                            .filter(s -> !s.isEmpty())
                            .map(Long::valueOf)
                            .toArray(Long[]::new);

            // 获取到货数量列表
            List<GcControlConfirmationPurchaseList> gcControlConfirmationPurchaseLists =
                    gcControlConfirmationPurchaseListMapper.selectTotalByPurchaseId(purchaseIdArray,gcControlPurchasePlan.getProcurementType());

            // 合并数据 - 以map的形式K是manage_id，V是总数量
            Map<Long, BigDecimal> arrivalQuantityMap = gcControlConfirmationPurchaseLists.stream()
                    .collect(Collectors.toMap(
                            GcControlConfirmationPurchaseList::getManageId,
                            GcControlConfirmationPurchaseList::getTotalArrivalQuantity
                    ));

            gcControlPlanLists.forEach(plan -> {
                BigDecimal quantity = arrivalQuantityMap.get(plan.getManageId());
                if (quantity != null) {
                    plan.setTotalArrivalQuantity(quantity);
                }
            });
        }
        gcControlPurchasePlan.setGcControlPlanList(gcControlPlanLists);
        return gcControlPurchasePlan;
    }

    /**
     * 查询成本控制--采购计划列表
     *
     * @param gcControlPurchasePlan 成本控制--采购计划
     * @return 成本控制--采购计划
     */
    @Override
    public List<GcControlPurchasePlan> selectGcControlPurchasePlanList(GcControlPurchasePlan gcControlPurchasePlan) {
        return gcControlPurchasePlanMapper.selectGcControlPurchasePlanList(gcControlPurchasePlan);
    }

    /**采购确认列表*/
    @Override
    public List<GcControlPurchasePlan> selectConfirmationList(GcControlPurchasePlan gcControlPurchasePlan) {
        // 1. 获取采购计划列表
        List<GcControlPurchasePlan> gcControlPurchasePlans = gcControlPurchasePlanMapper.selectGcControlPurchasePlanList(gcControlPurchasePlan);

        // 2. 获取采购数量和到货数量的统计结果
        List<GcControlPurchasePlan> purchasePlans = gcControlPurchasePlanMapper.selectGcControlPurchasePlanBYId(gcControlPurchasePlan.getProjectId());

        // 3. 创建 plan_id 到 purchaseQuantity 和 arrivalQuantity 的映射
        Map<Long, PurchasePlanStats> statsMap = new HashMap<>();
        for (GcControlPurchasePlan plan : purchasePlans) {
            statsMap.put(plan.getPlanId(), new PurchasePlanStats(plan.getPurchaseQuantity(), plan.getArrivalQuantity()));
        }

        // 4. 遍历每个采购计划，设置 planType 和确认采购列表
        for (GcControlPurchasePlan plan : gcControlPurchasePlans) {
            // 4.1 获取当前计划的统计信息
            PurchasePlanStats stats = statsMap.get(plan.getId());

            // 4.2 比较 purchaseQuantity 和 arrivalQuantity
            if (stats != null) {
                plan.setPlanType(String.valueOf(
                        stats.getPurchaseQuantity().compareTo(stats.getArrivalQuantity()) == 0
                ));
            } else {
                plan.setPlanType("false"); // 如果没有统计信息，默认设为 false
            }

            // 4.3 查询并设置确认采购列表
            List<GcControlConfirmationPurchase> confirmations = gcControlConfirmationPurchaseMapper.selectPurchaseList(plan.getId());
            plan.setControlConfirmationPurchaseList(confirmations);
        }
        return gcControlPurchasePlans;
    }

    // 辅助类，用于存储 purchaseQuantity 和 arrivalQuantity
    private static class PurchasePlanStats {
        private final BigDecimal purchaseQuantity;
        private final BigDecimal arrivalQuantity;

        public PurchasePlanStats(BigDecimal purchaseQuantity, BigDecimal arrivalQuantity) {
            this.purchaseQuantity = purchaseQuantity;
            this.arrivalQuantity = arrivalQuantity;
        }

        public BigDecimal getPurchaseQuantity() {
            return purchaseQuantity;
        }

        public BigDecimal getArrivalQuantity() {
            return arrivalQuantity;
        }
    }
    /**
     * 新增成本控制--采购计划
     *
     * @param gcControlPurchasePlan 成本控制--采购计划
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public GcControlPurchasePlan insertGcControlPurchasePlan(GcControlPurchasePlan gcControlPurchasePlan) {
        gcControlPurchasePlan.setApprovalStatus(BusinessStatusEnum.DRAFT.getStatusValue());
        gcControlPurchasePlan.setCreater(SecurityUtils.getUsername());
        gcControlPurchasePlan.setCreateTime(DateUtils.getNowDate());
        gcControlPurchasePlan.setPurchaseTime(DateUtils.getNowDate());
        gcControlPurchasePlanMapper.insertGcControlPurchasePlan(gcControlPurchasePlan);
        handler(gcControlPurchasePlan.getId(),gcControlPurchasePlan);
        return gcControlPurchasePlan;
    }

    /**
     * 修改成本控制--采购计划
     *
     * @param gcControlPurchasePlan 成本控制--采购计划
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGcControlPurchasePlan(GcControlPurchasePlan gcControlPurchasePlan) {
        gcControlPurchasePlan.setUpdater(SecurityUtils.getUsername());
        gcControlPurchasePlan.setUpdateTime(DateUtils.getNowDate());
        int i = gcControlPurchasePlanMapper.updateGcControlPurchasePlan(gcControlPurchasePlan);
        handler(gcControlPurchasePlan.getId(),gcControlPurchasePlan);
        return i;
    }

    /**
     * 批量删除成本控制--采购计划
     *
     * @param ids 需要删除的成本控制--采购计划主键
     * @return 结果
     */
    @Override
    public int deleteGcControlPurchasePlanByIds(Long[] ids) {
        return gcControlPurchasePlanMapper.deleteGcControlPurchasePlanByIds(ids);
    }

    /**
     * 删除成本控制--采购计划信息
     *
     * @param id 成本控制--采购计划主键
     * @return 结果
     */
    @Override
    public int deleteGcControlPurchasePlanById(Long id) {
        return gcControlPurchasePlanMapper.deleteGcControlPurchasePlanById(id);
    }


    /**
     * 保存数据
     * 1-清单管理
     */
    public void handler(Long id, GcControlPurchasePlan gcControlPurchasePlan) {
        /*清单列表对象*/
        List<GcControlPlanList> gcControlPlanList = gcControlPurchasePlan.getGcControlPlanList();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("projectId", gcControlPurchasePlan.getProjectId());
        params.put("procurementType", gcControlPurchasePlan.getProcurementType());
        /*根据plan_id查询是否存在数据，如果存在的话先删除再新增*/
        List<GcControlPlanList> gcControlPlanLists = gcControlPlanListMapper.selectGcControlPlanByIdList(params);
        if(CollectionUtil.isNotEmpty(gcControlPlanLists)){
            gcControlPlanListMapper.deleteControlPlanListByIds(gcControlPurchasePlan.getId());
        }
        for (GcControlPlanList controlPlanList : gcControlPlanList) {
            // ✅ 检查 purchaseQuantity 是否为 0 或 "0"（字符串）
            Object purchaseQuantity = controlPlanList.getPurchaseQuantity();
            if (purchaseQuantity == null || ((BigDecimal) purchaseQuantity).compareTo(BigDecimal.ZERO) == 0) {
                continue; // 跳过这条数据
            }
            controlPlanList.setProjectId(gcControlPurchasePlan.getProjectId());
            controlPlanList.setPlanId(id);
            controlPlanList.setProcurementType(gcControlPurchasePlan.getProcurementType());
            gcControlPlanListMapper.insertGcControlPlanList(controlPlanList);
        }
    }
}
